<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Ixudra\Curl\Facades\Curl;

class WechatController extends Controller
{
    /**
     * 连接微信服务器
     * @param Request $request
     * @return array|string
     */
    public function index(Request $request){
        $this->check($request); 
        if( $request->getMethod() == 'GET'){
            //绑定微信服务器
            return $request->input('echostr');
        }
        //处理消息
        $xml = $request->getContent();
        $parse = simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA | LIBXML_NOBLANKS);

    }

    /**
     * 获取access_token
     * @return mixed
     */
    public function getAccessToken(){
        if(Cache::has('access_token')){
            return Cache::get('access_token');
        }
        $appid = env('WECHAT_APPID');
        $secret = env('WECHAT_SECRET');
        $response = Curl::to('https://api.weixin.qq.com/cgi-bin/token')
            ->withData([
                'grant_type' => 'client_credential',
                'appid' => $appid,
                'secret' => $secret
            ])->get();
        $response = json_decode($response,true);
        if($response['access_token']){
            Cache::put('access_token', $response['access_token'], 110);
            return Cache::get('access_token');
        }
    }

    public function test(){
        $response = Curl::to('https://api.weixin.qq.com/semantic/semproxy/search?access_token='.Cache::get('access_token'))
            ->withData([
                "query" => "查一下明天从成都到上海的东方航空机票",
                "city" => "成都",
                "category" => "flight",
                "appid" => env('WECHAT_APPID'),
                "uid" => "123456"
            ])
            ->asJson()
            ->post();
        dd($response);
    }

    /**
     * 微信的验证
     * @param Request $request
     * @throws \ErrorException
     */
    public function check(Request $request)
    {
        $token = env('WECHAT_TOKEN','weixin');
        $check = $request->only(['timestamp','nonce']);
        $check['token'] = $token;
        sort($check, SORT_STRING);
        $hash = sha1(implode($check));
        if( $hash != $request->input('signature')){
            throw new \ErrorException("错误请求",403);
        }
    }
}
